<template>
  <div class="list">
    <table class="tb">
      <tr>
        <th>
          <input type="checkbox" v-model="checkall" @click="qx" />
        </th>
        <th>产品图片</th>
        <th>编号</th>
        <th>品牌名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>总计</th>
        <th>操作</th>
      </tr>
      <tr v-for="item in data" :key="item.id">
        <td>
          <input type="checkbox" v-model="checkarr" :value="item" />
        </td>
        <td>
          <img :src="item.imgSrc" width="50" height="50" />
        </td>
        <td>
          {{ item.code }}
        </td>
        <td>
          {{ item.productName }}
        </td>
        <td>
          {{ item.price }}
        </td>
        <td>
          <button v-dis:[item.count] @click="jian(item)">-</button>
          &nbsp;
          {{ item.count }}
          &nbsp;
          <button @click="jia(item)">+</button>
        </td>
        <td>
          {{ item.total }}
        </td>
        <td>
          <button @click="del(item.id)">删除</button>
        </td>
      </tr>
    </table>
    <div class="add" v-show="!data.length" :style="{ textAlign: 'center' }">
      没有更多数据了
    </div>
    <div class="add" :style="{ textAlign: 'center', color: 'red' }">
      总价格:
      <h1>{{ tot }}</h1>
    </div>
  </div>
</template>

<script>
export default {
  props: ["data"],

  data() {
    return {
      checkarr: [],
      checkall: false,
    };
  },
  watch: {
    checkarr(newval) {
      console.log(newval);
      if (this.data.length === newval.length) {
        this.checkall = true;
      } else {
        this.checkall = false;
      }
    },
  },
  directives: {
    dis: {
      inserted(el, binding) {
        console.log(binding);
        if (binding.arg === 1) {
          el.disabled = true;
        }
      },
      update(el, binding) {
        if (binding.arg > 1) {
          el.disabled = false;
        } else {
          el.disabled = true;
        }
      },
    },
  },
  computed: {
    tot() {
      return this.data
        .reduce((total, item) => {
          let itemTotal = parseFloat(item.total);
          return (total += itemTotal);

          // total+= parseFloat(item.total)
          // console.log(total)
        }, 0)
        .toFixed(2);
    },
  },
  methods: {
    zongjia(item) {
      item.total = (item.count * item.price).toFixed(2);
    },
    del(id) {
      this.$emit("del", id);
    },

    jia(item) {
      item.count++;
      this.zongjia(item);
    },
    jian(item) {
      item.count--;
      this.zongjia(item);
    },
    qx(e) {
      console.log(123);
      console.log(e.target.checked);
      let vl = e.target.checked;
      if (vl) {
        this.checkarr = this.data;
      } else {
        this.checkarr = [];
      }
    },
  },
};
</script>
